package com.laoniu.config;

import com.alibaba.fastjson.JSONObject;
import com.laoniu.annotation.OperateLog;
import com.laoniu.service.sys.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
public class OperateLogAspect {

    @Autowired
    private LogService logService;

    /**
     * 定义切面
     */
    @Pointcut("@annotation(com.laoniu.annotation.OperateLog)")
    public void operateLogPointCut(){

    }

    /**
     * 打印日志
     * @param point
     * @param keys
     */
    @AfterReturning(value = "operateLogPointCut()", returning = "keys")
    public void saveOperateLog(JoinPoint point, Object keys){
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        OperateLog annotation = method.getAnnotation(OperateLog.class);
        Object[] args = point.getArgs();
        //添加到日志表
        logService.insertLog(annotation.bizName(), JSONObject.toJSONString(args), annotation.operateType(), annotation.operateDesc());
    }
}
